package com.youtellv1.utils;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

public class SignDateUtils {

    /**
     * 判断某日期是否为周末（周六或周日）
     */
    public static boolean isWeekend(LocalDate date) {
        DayOfWeek day = date.getDayOfWeek();
        return day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY;
    }

    /**
     * 计算连续签到的工作日天数（从今天起倒序，不含周末）
     * @param signDates 已签到日期列表（Date 类型）
     * @return 连续签到天数
     */
    public static int calculateContinuousWorkdaySignIns(List<Date> signDates) {
        if (signDates == null || signDates.isEmpty()) {
            return 0;
        }

        // 转为 LocalDate 并倒序排序（从最近往前推）
        List<LocalDate> sortedDates = signDates.stream()
                .map(date -> date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());

        Set<LocalDate> signedSet = new HashSet<>(sortedDates); // 提高查询效率
        int count = 0;
        LocalDate current = LocalDate.now();

        while (true) {
            if (isWeekend(current)) {
                current = current.minusDays(1);
                continue;
            }
            if (signedSet.contains(current)) {
                count++;
                current = current.minusDays(1);
            } else {
                break; // 一旦断签，就终止
            }
        }

        return count;
    }
}
